<template>
  <div class="companyinfo-container">
    <el-form :model="companyInfoForm"
             status-icon
             :rules="formRules"
             ref="companyInfoForm"
             label-width="150px">
      <!-- <el-input v-model="companyInfoForm.company_type"></el-input> -->
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="单位类型"
                        prop="company_type">
            <el-select v-model="companyInfoForm.company_type"
                       style="width:100%"
                       disabled>
              <el-option v-for="item in companyTypeOptions"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->

      <el-row>
        <el-col :span="12">
          <el-form-item label="业务类型"
                        prop="business_type">
            <el-select v-model="companyInfoForm.business_type"
                       multiple
                       placeholder="请选择业务类型">
              <el-option v-for="item in businessTypeArr"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item prop=""
                        v-if="userInfo.company_business_type === '1'"
                        class="formItem"
                        label="监管级别">
            <el-select v-model="companyInfoForm.regulatory_level"
                       class="unit-name"
                       placeholder="请选择监管级别">
              <el-option v-for="item in superviseArr"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="单位名称"
                        prop="company_name">
            <el-input v-model="companyInfoForm.company_name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="单位简称"
                        prop="small_name">
            <el-input v-model="companyInfoForm.small_name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="二级域名前缀"
                        prop="company_domain">
            <label for>http://</label>
            <el-input class="col-4"
                      v-model="companyInfoForm.company_domain"></el-input>
            <!-- <label for>.ihibuilding.cn</label> -->
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人名称"
                        prop="contact_name">
            <el-input v-model="companyInfoForm.contact_name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人电话"
                        prop="contact_phone">
            <el-input v-model="companyInfoForm.contact_phone"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row>
        <el-col :span='12'>
          <el-form-item label='单位等级'
                        prop='company_level'
                        required>

            <el-select v-model='companyInfoForm.company_level'>
              <el-option label="请选择单位等级"
                         value="0">
              </el-option>
              <el-option label="总公司"
                         value="1">
              </el-option>
              <el-option label="分公司"
                         value="2">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>-->

      <el-row>
        <el-col :span="12">
          <el-form-item label="单位logo"
                        prop="company_logo">
            <el-upload class="company-logo-upload"
                       :http-request="upload"
                       action
                       :show-file-list="false"
                       :on-success="handleCompanylogoSuccess"
                       :before-upload="beforeCompanylogoUpload"
                       :data="companyLogoInfo"
                       accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PBG, .GIF">
              <img :src="companyInfoForm.company_logo"
                   v-if="companyInfoForm.company_logo"
                   class="logo" />
              <i v-else
                 class="el-icon-plus logo-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="单位邀请码">
            <span>{{invite_code}}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="二维码">
            <div class="div-qrcode">
              <img class="qrcode"
                   :src="qrcodeUrl"
                   alt="">
              <el-button type="success"
                         class="success-type"
                         @click="onDownQrcode">下载</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-row>
        <el-col :span='12'>
          <el-form-item label='平台主题'
                        prop='platform_theme'
                        required>
            <el-input v-model='companyInfoForm.platform_theme'>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>-->

      <el-row>
        <el-col :span='14'>
          <el-form-item label='单位地址'
                        prop='area_no'>
            <LocationSelect :locaData.sync="companyInfoForm"></LocationSelect>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="详细地址"
                        prop="addr">
            <el-input v-model="companyInfoForm.addr"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="具体位置"
                        prop="lonlat">
            <el-input readonly
                      :value="companyInfoForm.lonlat"
                      @focus="selectMap"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="单位邮箱"
                        prop="mail">
            <el-input v-model="companyInfoForm.mail"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="法人姓名"
                        prop="legal_name">
            <el-input v-model="companyInfoForm.legal_name"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="证件类型"
                        prop="legal_card_type">
            <el-select v-model="companyInfoForm.legal_card_type">
              <el-option v-for="(item, index) in legalCardCode"
                         :value="item.value"
                         :label="item.name"
                         :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="证件号码"
                        prop="legal_card_no">
            <el-input v-model="companyInfoForm.legal_card_no"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="统一社会信用代码"
                        prop="credit_code">
            <el-input v-model="companyInfoForm.credit_code"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="营业执照电子版"
                        prop="credit_img">
            <el-upload class="company-logo-upload"
                       :http-request="uploadCreditImg"
                       action
                       :show-file-list="false"
                       :on-success="handleCompanylogoSuccess"
                       :before-upload="beforeCompanylogoUpload"
                       :data="creditImg"
                       accept="jpg, .jpeg, .png, .gif, .bmp, .pdf, .JPG, .JPEG, .PBG, .GIF">
              <img :src="companyInfoForm.credit_img"
                   v-if="companyInfoForm.credit_img"
                   class="logo" />
              <i v-else
                 class="el-icon-plus logo-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="网站logo"
                        prop="image_picture">
            <el-upload class="company-logo-upload"
                       :http-request="uploadWebsiteLogo"
                       action
                       :show-file-list="false"
                       :on-success="handleCompanylogoSuccess"
                       :before-upload="beforeCompanylogoUpload"
                       :data="websiteLogo"
                       accept="jpg, .jpeg, .png, .gif, .bmp, .pdf, .JPG, .JPEG, .PBG, .GIF">
              <img :src="companyInfoForm.image_picture"
                   v-if="companyInfoForm.image_picture"
                   class="logo" />
              <i v-else
                 class="el-icon-plus logo-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="12"
              align="center">
        <el-button @click="updateCompanyInfo('companyInfoForm')"
                   type="primary"
                   icon="el-icon-document">保存</el-button>
        <el-button @click="back">取消</el-button>
      </el-col>
    </el-row>
    <Map :mapLngLat.sync="companyInfoForm"
         :dialogVisible.sync="mapDialogVisible"></Map>
  </div>
</template>
<script>
import LocationSelect from '@/components/LocationSelect/LocationSelect'
import { locationData } from '@/assets/json/locationData'
import { companyInfoApi } from '@/services/CompanySetting'
import { UploadFileApi } from '@/services/UserPermission'
import { standardCodeApi } from '@/services/StandardCode'
import { accountApi } from '@/services/CompanySetting'
import Map from '@/components/Map/Map'
export default {
  data () {
    let mobileRule = (rule, value, callback) => {
      let reg = /^1[3|4|5|7|8][0-9]\d{8}$/
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (reg.test(value) === false) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    let mailRule = (rule, value, callback) => {
      let reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (reg.test(value) === false) {
        callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }

    return {
      userInfo: {},
      businessTypeArr: [],//业务类型标准码
      qrcodeUrl: '', //二维码
      requestParam: {
        page: 1,
        page_size: 10
      },
      superviseArr: [{
        value: '1',
        name: '省级'
      }, {
        value: '2',
        name: '市级'
      }, {
        value: '3',
        name: '县级'
      }],
      access_token: '',
      companyInfoForm: {
        regulatory_level: '',
        business_type: [],//业务类型
        company_type: '',
        company_name: '',
        small_name: '',
        company_domain: '',
        contact_name: '',
        contact_phone: '',
        company_level: '',
        company_logo: '',
        platform_theme: '',
        company_address: {},
        addr: '',
        detailAddress: '',
        mail: '',
        legal_name: '',
        legal_card_type: '',
        legal_card_no: '',
        credit_code: '',
        credit_img: '',
        image_picture: '',
        lonlat: '',
        lon: '',
        lat: '',
        area: ''
      },
      companyTypeOptions: [],
      // 表单验证规则
      formRules: {
        business_type: [
          { required: true, message: '业务类型不能为空', trigger: 'blur' }
        ],
        // company_type: [
        //   { required: true, message: '请选择单位类型', trigger: 'change' }
        // ],
        company_name: [
          { required: true, message: '请输入单位名称', trigger: 'blur' }
        ],
        small_name: [
          { required: true, message: '请输入单位简称', trigger: 'blur' }
        ],
        company_domain: [
          { required: true, message: '请输入二级域名前缀', trigger: 'blur' }
        ],
        // contact_name: [
        //   { required: true, message: '请输入负责人名称', trigger: 'blur' }
        // ],
        // contact_phone: [
        //   { required: true, message: '请输入负责人电话', trigger: 'blur' }
        // ],
        area_no: [{ required: true, message: '请选择单位地址', trigger: 'change' }],
        addr: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        area: [{ required: true, message: '请输入地址', trigger: 'change' }],
        lonlat: [
          { required: true, message: '请输入具体位置', trigger: 'blur' }
        ],
        mail: [{ trigger: 'blur', validator: mailRule }],
        // legal_name: [
        //   { required: true, message: '请输入法人姓名', trigger: 'blur' }
        // ],
        // legal_card_type: [
        //   { required: true, message: '请选择证件类型', trigger: 'blur' }
        // ],
        // legal_card_no: [
        //   { required: true, message: '请输入证件号码', trigger: 'blur' }
        // ],
        // credit_code: [
        //   { required: true, message: '请输入统一社会信用代码', trigger: 'blur' }
        // ],
        // credit_img: [
        //   { required: true, message: '请上传营业执照', trigger: 'blur' }
        // ],
        // image_picture: [
        //   { required: true, message: '请上传网站logo', trigger: 'blur' }
        // ]
      },
      provinceList: [],
      cityList: [],
      areaList: [],
      mapDialogVisible: false,
      companyLogoInfo: {},
      creditImg: {},
      websiteLogo: {},
      // 证件类型标准码
      legalCardCode: [],
      company_id: '',
      invite_code: '',
    }
  },
  props: {
    codeType: String
  },
  components: {
    LocationSelect,
    Map
  },
  watch: {
    companyInfoForm: {
      handler (newval, oldval) {
        // console.log(newval, 'watch companyinfo')
      },
      deep: true
    }
  },
  computed: {
    getProjectIdList () {
      let store = this.$store.state.getProjectIdList
      let local = window.localStorage.getItem('projectIdList') || []
      if (!store) {
        store = local
      }
      // console.log(store, 'project id list')
      return store
    }
  },
  methods: {
    getBusinessType () {//业务类型
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'businessType'
        }
      }).then((res) => {
        if (res.data) {
          this.businessTypeArr = res.data.list;//业务类型
          window.localStorage.setItem('businessTypeArr', JSON.stringify(this.businessTypeArr))
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    //生成二维码
    bindQRCode () {
      accountApi.getQrcode({
        data: {
          id: this.company_id,
          node_type: 1,//'2'
        }
      }).then(res => {
        let a = document.createElement("a");
        let blob = new Blob([res], { type: 'image/png' })
        let url = URL.createObjectURL(blob)
        this.qrcodeUrl = url;
      }, err => {
        console.log(err)
      }
      )
    },
    // //生成二维码
    // bindQRCode () {
    //   let userInfo = window.localStorage.getItem('userInfo') || '{}'
    //   userInfo = JSON.parse(userInfo)
    //   accountApi.getUserQRCode({
    //     data: {
    //       company_id: this.company_id,
    //       type: 'user',
    //       text: userInfo.user_id,
    //       footer: '单位邀请码：{邀请码},{单位名称}'
    //     }
    //   }).then(res => {
    //     let a = document.createElement("a");
    //     let blob = new Blob([res], { type: 'image/png' })
    //     let url = URL.createObjectURL(blob)
    //     this.qrcodeUrl = url
    //   })
    // },
    //下载邀请码二维码
    onDownQrcode () {
      let a = document.createElement('a')
      a.href = this.qrcodeUrl;
      a.download = '二维码';
      a.click()
      this.$message({
        message: "正在进行下载保存",
        type: 'success'
      })
    },
    back () {
      this.$router.go(-1)
    },
    // 上传单位logo
    upload (file) {
      let formData = new FormData()
      formData.append('module', 'industry')
      formData.append('pic_file_apk', file.file)
      UploadFileApi.uploadFile({
        data: formData
      }).then(res => {
        if (res.data) {
          this.companyInfoForm.company_logo = res.data.file_path
        }
      })
    },
    // 上传营业执照电子版
    uploadCreditImg (file) {
      let formData = new FormData()
      formData.append('module', 'industry')
      formData.append('pic_file_apk', file.file)
      UploadFileApi.uploadFile({
        data: formData
      }).then(res => {
        if (res.data) {
          this.companyInfoForm.credit_img = res.data.file_path
        }
      })
    },
    // 上传网站封面图
    uploadWebsiteLogo (file) {
      let formData = new FormData()
      formData.append('module', 'industry')
      formData.append('pic_file_apk', file.file)
      UploadFileApi.uploadFile({
        data: formData
      }).then(res => {
        if (res.data) {
          this.companyInfoForm.image_picture = res.data.file_path
        }
      })
    },
    handlePageChange (page) { },
    handleCompanylogoSuccess () { },
    beforeCompanylogoUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isGIF = file.type === 'image/gif'
      const isPNG = file.type === 'image/png'
      const isBMP = file.type === 'image/bmp'
      const isPDF = file.type === 'image/pdf'

      if (!isJPG && !isGIF && !isPNG && !isBMP && !isPDF) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP/PDF 格式!')
      }
      return isJPG || isBMP || isGIF || isPNG || isPDF
    },
    // 处理省市区数据
    handleLocationData () {
      this.provinceList = []
      this.cityList = []
      this.areaList = []
      locationData.map(item => {
        this.provinceList.push(item)
      })
    },
    // 选择省份
    chooseProvince (item) {
      this.cityList = item.children
    },
    // 选择城市
    chooseCity (item) {
      this.areaList = item.children
    },
    // 选择区域
    chooseArea () { },
    // 选择具体经纬度
    selectMap () {
      this.mapDialogVisible = true
    },
    getBusinessTypeFunc (arr) {//业务类型
      let arrV = [];
      if (arr && arr.length > 0) {
        arr.map((item) => {
          arrV.push(item.company_type);//业务类型
        })
      };
      console.log('业务类型arrV=', arrV)
      return arrV;
    },
    // 获取公司信息
    getCompanyInfo () {
      companyInfoApi.getCompanyInfo().then(
        res => {
          this.companyInfoForm = res.data
          let businessType = this.companyInfoForm.business_type_list;//业务类型
          this.$set(this.companyInfoForm, 'business_type', []);
          this.companyInfoForm.business_type = this.getBusinessTypeFunc(businessType);//业务类型
          this.company_id = res.data.company_id;
          this.invite_code = res.data.invite_code;
          this.companyInfoForm.lonlat =
            this.companyInfoForm.jd + '-' + this.companyInfoForm.wd
          this.companyInfoForm.lon = this.companyInfoForm.jd
          this.companyInfoForm.lat = this.companyInfoForm.wd
          this.$nextTick(() => {
            this.bindQRCode();//生成二维码
          })
        },
        err => {
          console.log(err)
        }
      )
    },
    // 获取单位类型
    getCompanyType () {
      standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: 'companyType'
          }
        })
        .then(res => {
          this.companyTypeOptions = res.data.list
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 编辑公司信息
    updateCompanyInfo (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // this.companyInfoForm.company_logo = this.companyInfoForm.company_logo.replace(
          //   /^http:\/\/[^/]+/,
          //   ''
          // )
          // this.companyInfoForm.credit_img = this.companyInfoForm.credit_img.replace(
          //   /^http:\/\/[^/]+/,
          //   ''
          // )
          // this.companyInfoForm.image_picture = this.companyInfoForm.image_picture.replace(
          //   /^http:\/\/[^/]+/,
          //   ''
          // )
          this.companyInfoForm.jd = this.companyInfoForm.lon;
          this.companyInfoForm.wd = this.companyInfoForm.lat;

          let obj = Object.assign({}, this.companyInfoForm);
          obj.business_types = obj.business_type.join(',');
          this.$delete(obj, 'business_type');
          companyInfoApi
            .updateCompanyInfo({
              data: obj
            })
            .then(
              res => {
                if (res.code === 0) {
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                  this.getCompanyInfo()
                } else {
                  this.$message(res.msg)
                }
              },
              err => {
                console.log(err)
              }
            )
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 获取证件类型标准码
    getLegalCardCode () {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: 'legalCardType'
          }
        })
        .then(res => {
          if (res.code === 0) {
            this.legalCardCode = res.data.list
            window.localStorage.setItem('legalCard', JSON.stringify(res.data.list))
          }
        })
        .catch(error => {
          console.log(error)
        })
    }
  },
  async created () {
    let userInfo = window.localStorage.getItem('userInfo') || '{}'
    this.userInfo = JSON.parse(userInfo)
    this.userInfo.company_business_type = '1'
    let businessTypeAr = JSON.parse(window.localStorage.getItem('businessTypeArr'));
    if (businessTypeAr) {//业务类型
      this.businessTypeArr = businessTypeAr;
    } else {
      await this.getBusinessType();//业务范围
    }
    // this.access_token = sessionStorage.getItem('access_token')
    this.access_token = localStorage.getItem('access_token')
    let legalCardLocal = window.localStorage.getItem('legalCard')
    if (legalCardLocal) {
      this.legalCardCode = JSON.parse(legalCardLocal)
    } else {
      await this.getLegalCardCode()
    }
    // console.log(this.access_token)
    // if (window.sessionStorage.getItem('access_token')) {
    if (window.localStorage.getItem('access_token')) {
      this.getLegalCardCode()
      this.handleLocationData()
      this.getCompanyInfo()
      // this.getCompanyType()
    }
  },
  mounted () { }
}
</script>
<style scoped lang='scss'>
.companyinfo-container {
  padding: 15px;
  .el-select {
    width: 100%;
  }
  .company-logo-upload {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
    .logo-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .logo {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  .div-qrcode img {
    width: 200px;
    height: 200px;
  }
  .success-type {
    background-color: #409eff;
    border-color: #409eff;
  }
}
</style>
